<?php
/**
 * @since v1.0
 * @modify 2015.6.21
 * @copyright 深圳亿游
 */
require_once(LIB_PATH.'controller/root.con.php');
function mySortVisitor($a,$b){
    if ($a['created']==$b['created']) return 0;
    return ($a['created']<$b['created'])?1:-1;
}
class messageCon extends rootCon
{
    public function listUserAction(){
        $uid = mylogin::getUid(true);
        if(r('isDebug')){
            $uid = 1;
        }
        $message = new Message();
        $message->load();
        $con = $message->getConByLoad();
        if($con) $con = "  AND $con ";

        $sql = "SELECT fromUid  FROM ".$message->table()." WHERE status=".STATUS_PUBLISH." AND fromUid >0  AND toUid=$uid $con  GROUP BY fromUid ";
        $allResult = $message->query($sql);
        $fromUids = [];
        foreach($allResult as $item){
            $fromUids[] = $item['fromUid'];
        }


        $sql = "SELECT toUid  FROM ".$message->table()." WHERE status=".STATUS_PUBLISH." AND toUid >0  AND fromUid=$uid $con  GROUP BY toUid ";
        $allResult = $message->query($sql);
        foreach($allResult as $item){
            $fromUids[] = $item['toUid'];
        }
        $fromUids = array_unique($fromUids);

        $result = [];
        $i = 0;
        foreach($fromUids as $fromUid){
            $tempObj = new Message();
            $sql = "SELECT COUNT(1) AS NUM FROM ".$tempObj->table()." WHERE fromUid=$fromUid  AND toUid=$uid AND readStatus=0";
            $one = $tempObj->one($sql);
            $result['list'][$i]['messageCount'] = intval($one['NUM']);


            $tempObj = new Message();
            $sql = "SELECT * FROM ".$tempObj->table()." WHERE (fromUid=$fromUid  AND toUid=$uid) OR (fromUid=$uid  AND toUid=$fromUid)   ORDER BY created DESC LIMIT 1";
            $one = $tempObj->one($sql);
            if($one['fromUid'] == $uid){
                $result['list'][$i]['fromNick']   = $one['toNick'];
                $result['list'][$i]['fromUid']    = $one['toUid'];
                $result['list'][$i]['fromAvatar'] = $one['toAvatar'];
                $result['list'][$i]['created']      = $one['created'];
                $result['list'][$i]['msg']          = $one['msg'];
            }else{
                $result['list'][$i]['fromNick']   = $one['fromNick'];
                $result['list'][$i]['fromUid']    = $one['fromUid'];
                $result['list'][$i]['fromAvatar'] = $one['fromAvatar'];
                $result['list'][$i]['created']      = $one['created'];
                $result['list'][$i]['msg']          = $one['msg'];
            }

            if(!$result['list'][$i]['fromAvatar']){
                $user = new User();
                $user->find($result['list'][$i]['fromUid']);
                if($user->nick){
                    $result['list'][$i]['fromNick'] = $user->nick;
                }else {
                    $result['list'][$i]['fromNick'] = "访客";
                }
                if($user->avatar){//新授权的用户
                    $result['list'][$i]['fromAvatar'] = $user->avatar;

                    //更新老的数据
                    $obj = new Message();
                    $sql = "UPDATE tbl_message SET fromNick ='".addslashes($user->nick)."',fromAvatar='{$user->avatar}' WHERE fromUid=".$user->uid;
                    $obj->query($sql);

                    $sql = "UPDATE tbl_message SET toNick ='".addslashes($user->nick)."',toAvatar='{$user->avatar}' WHERE toUid=".$user->uid;
                    $obj->query($sql);
 
                }else{
                    $result['list'][$i]['fromAvatar'] = "/default.png";
                }

            }
            
            $i++;
        }//end foreach
        $list = $result['list'];
        if($list) {
	        usort($list,'mySortVisitor');
        }
        $result['list'] =  $list;


        $result['fromUids']  = $fromUids;


        $this->j(0, "list",$result);
    }

    public function listAction() {
        $uid = mylogin::getUid(true);
        if(r('isDebug')){
            $uid = 1;
        }


        $message = new Message();
        $fromUid = r_int('fromUid');
        if($fromUid){
            $con = "  AND (fromUid = $fromUid OR toUid=$fromUid) ";
        }


        $sql = "SELECT * FROM ".$message->table()." WHERE status=".STATUS_PUBLISH." AND (fromUid=$uid OR toUid=$uid) $con";
        $result = $message->pager($sql,20,"created DESC");




        $i = 0;
        $allIds = [-1];
        foreach($result['list'] as $item){
            $result['list'][$i]['created'] = mydate::getCnTime($result['list'][$i]['created']);
            if($item['readStatus']==0) $allIds[] = $item['messageId'];
            $i++;
        }

        if(count($allIds)>1 && $fromUid){
            $msgIdStr = join(",",$allIds);
            $sql = "UPDATE tbl_message SET readStatus=1 WHERE messageId IN ($msgIdStr)";
            $message->query($sql);
        }

        if($fromUid){
            $user = new User();
            $user->find($fromUid);
            $result['fromNick']   = $user->nick;
            $result['fromAvatar'] = $user->avatar;
        }

        $this->j(0, "list",$result);
    }

    //发送消息
    //测试
    //https://zhaopeixunapi.hkbao.com/message,send?fromUid=28&toUid=28&msg=good&key=111&time=11111111&isDebug=1
    public function sendAction(){
        $time = r('time');
        $fromUid = r('fromUid');
        $toUid   = r('toUid');
        $expectKey = mylogin::getMd5Pwd($fromUid.'-'.$toUid.$time);
        if($expectKey!=r('key')){
            if(!r('isDebug')) $this->j(-1,"keyError");
        }

        $user = new User();
        $user->find(r_int('toUid'));
        $msg = r('msg');
        myxiaochengxu::sendXiaochengxuCard($user->openId,$msg);
    }


    public function saveFormIdAction(){
        $uid = mylogin::getUid(true);
        $messageKey = new MessageKey();
        $messageKey->uid = $uid;
        $messageKey->messageKey = r('formId');
        $messageKey->keyType = 2;//表示表单
        $reg = "/mock one/i";
        $match = preg_match($reg,$messageKey->messageKey);
        if(!$match){
            $saved = $messageKey->save();
            $this->j(0,'',['saved'=>$saved]);
        }else{
            $this->j(0,'',['saved'=>false,'mock'=>true]);
        }       
    }

}



